<?php

namespace app\models;

use app\common\ExceptionHandler;
use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%shop_member}}".
 *
 * @property int $id
 * @property string $name
 * @property string $password
 * @property string $email
 * @property int $updated
 * @property int $created
 */
class ShopMember extends \yii\db\ActiveRecord implements IdentityInterface
{
    use Common;
    const SCENARIO_STORE ='store';
    const SCENARIO_UPDATE='update';

    /*附表数据，用户基本信息*/
    public $true_name;
    public $age;
    public $sex;
    public $birthday;

    private $scriptTime;//脚本开始时间
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->scriptTime=time();
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%shop_member}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['id','required','message'=>'id不能为空','on'=>[
                self::SCENARIO_UPDATE]
            ],
            ['name','required','message'=>'账号不能为空','on'=>[
                self::SCENARIO_STORE]
            ],
            ['name','validateNameExist','message'=>'用户名已经存在','on'=>[
                self::SCENARIO_STORE]
            ],
            ['password','required','message'=>'密码不能为空','on'=>[
                self::SCENARIO_STORE,
                ]
            ],
            ['email','required','message'=>'邮箱不能为空','on'=>[
                self::SCENARIO_STORE]
            ],
            ['email','email','message'=>'邮箱格式不正确','on'=>[
                self::SCENARIO_STORE]
            ],
        ];

    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'password' => 'Password',
            'email' => 'Email',
            'updated' => 'Updated',
            'created' => 'Created',
        ];
    }

    /**
     * 获取用户信息
     */
    public function getProfile()
    {
        return $this->hasOne(ShopMemberProfile::class,['shop_member_id'=>'id'])->asArray();
    }


    /**
     * 检查用户是否已经存在
     */
    public function validateNameExist()
    {
        //已经有错误了，则不进行验证了
        if($this->hasErrors())return;

        //查找用户名是否已经存在
        self::findOne(['name'=>$this->name]) && $this->addError('name','用户名已被使用');
    }


    /**
     * 添加会员
     */
    public function storeManager($data)
    {

        $this->loadData($data,SCENARIO_STORE);

        //开事务
        $trance=Yii::$app->db->beginTransaction();
        try{

            $this->updated=$this->scriptTime;
            $this->created=$this->scriptTime;

            !($id=$this->save()) && ExceptionHandler::throwCode(1009);

            $profileData['shop_member_id']=$id;
            /*附表数据*/
            $this->true_name && $profileData['true_name']=$this->true_name;
            $this->age && $profileData['age']=$this->age;
            $this->sex && $profileData['sex']=$this->sex;
            $this->birthday && $profileData['birthday']=$this->birthday;
            $profile['ShopMemberProfile']=$profileData;

            /*附表数据*/
            $profileModel=new ShopMemberProfile();
            !$profileModel->load($profile) && ExceptionHandler::throwCode(1003);


            $profileModel->updated=$this->scriptTime;
            $profileModel->created=$this->scriptTime;
            !$profileModel->save() && ExceptionHandler::throwCode(1009);
            //if(!$profileModel->save()) print_r($profileModel->errors);

            $trance->commit();
        }catch (\Exception $e){
            $trance->rollBack();
            throw $e;
        }

    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['password'=>$token]);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey()===$authKey;
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->auth_key=Yii::$app->security->generateRandomString();
            }
            return true;
        }

        return false;
    }

    /**
     * 通过用户名称查找用户
     */
    public static function findByUsername($userName)
    {
        return self::findOne(['name'=>$userName]);
    }


}
